<?php

namespace app\api\model\service;

use think\Exception;
use think\Model;
use fast\Random;

class PremiumOrder extends Model
{
    // 表名
    protected $name = 'service_premium_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 创建支付差价订单
     * @param $params
     * @return array
     * @throws Exception
     */
    public static function createOrder($params)
    {
        $userMoney = User::getMoney($params['user_id']);
        if($params['paytype'] == 4 && $userMoney<$params['payprice'])
        {
            throw new Exception('余额不足,请及时充值');
        }
        $params['orderId'] = 'Premium'.Random::alnum(4).'-'.$params['user_id'].'-'.time();
        $premiumOrder = new PremiumOrder($params);
        $premiumOrder->allowField(true)->save();
        $re['paystatus'] = 0;
        if($params['paytype'] != 4)
        {
            $re['pay'] = \addons\service\library\Pay::payOrder(['amount'=>$params['payprice'],'orderid'=>$params['orderId'],'title'=>'支付补差价费用'],$params['paytype'],$params['user_id'],0);
        }else{
            User::money(-$params['payprice'],$params['user_id'],'支付项目差价');
            $premiumOrder->save(['state'=>1,'paytime'=>time()],['id'=>$premiumOrder->id]);
            self::finishPay($premiumOrder->id);
            $re['paystatus'] = 1;
            $re['pay'] = '';
        }
        return $re;
    }


    public static function finishPay($id)
    {
        $premiumOrder = self::where(['id'=>$id,'state'=>1])->field('id,order_id,payprice,user_id')->find();
        if(!$premiumOrder)
        {
            return false;
        }
        $order = Order::where(['id'=>$premiumOrder['order_id']])->field('id,payprice,premium_price,settle_price')->find();
        $payprice = bcadd($order['payprice'],$premiumOrder['payprice'],2);
        $premiumPrice = bcadd($order['premium_price'],$premiumOrder['payprice'],2);
        $settlePrice = bcadd($order['settle_price'],$premiumOrder['payprice'],2);
        Order::where(['id'=>$premiumOrder['order_id']])->update(['payprice'=>$payprice,'premium_price'=>$premiumPrice,'settle_price'=>$settlePrice,'updatetime'=>time()]);
        OrderLog::create(['order_id'=>$premiumOrder['order_id'],'user_id'=>$premiumOrder['user_id'],'type'=>12,'content'=>'订单已补差价']);
        return true;
    }


}


